import React, {useState, useEffect, useRef} from 'react';
import {
  View,
  Text,
  TextInput,
  ScrollView,
  StyleSheet,
  Image
} from 'react-native';
import io from 'socket.io-client';
const SERVER_URL = 'http://192.168.180.211:8080';
import AsyncStorage from '@react-native-async-storage/async-storage';
// 一对一聊天：首先拿到当前用胡和聊天对象的信息，当前用户的信息在登陆成功的时候被保存在了dva里面
import {IUserInfo} from '@/models/user';
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from '@/models/index';
import Touchable from '../../components/Touchable';
import IconFont, {IconNames} from '../../assets/iconfont';
import Toast from 'react-native-root-toast';

const mapStateToProps = ({users}: RootState) => {
  return {
    photographerInfo: users?.photographerInfoByName,
  };
};
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState {
  navigation: {goBack: any; navigate: any};
  // route: {params: {selectedId: string}};
  route: any;
}
interface IMessageObj {
    username:string,
    text:string;
    createTime:string,
    scurpture:string,
    isSender:boolean
}
const Chat = (props: IProps) => {
  const [messages, setMessages] = useState<IMessageObj[]>([]);
  const [message, setMessage] = useState<string>('');
  const [currentUser, setCurrentUser] = useState<IUserInfo>({});
  const [chatMan, setChatMan] = useState<IUserInfo>({});
  const [onLine,setOnLine] = useState<boolean>(true);
  const currentUserRef = useRef<IUserInfo>();
  currentUserRef.current = currentUser;
  const chatManRef = useRef<IUserInfo>();
  chatManRef.current = chatMan;
  const messagesRef = useRef<IMessageObj[]>();
  messagesRef.current = messages;
  const scrollViewRef = useRef<any>();

  const {route, photographerInfo, navigation} = props;
  // io的第一个参数是连接服务器的url
  let socket = io(SERVER_URL);

  // 获取当前用户
  const getCurrentUserInfo = async () => {
    let currentUserInfo: string | null = '';
    currentUserInfo = await AsyncStorage.getItem('currentUserInfo');
    if (currentUserInfo) {
      setCurrentUser(JSON.parse(currentUserInfo));
    }
  };
  useEffect(() => {
    // 获取聊天对象
    let chatMan: IUserInfo[] | undefined = [];
    chatMan = photographerInfo?.filter(item => {
      return item._id === route.params.selectedId;
    });
    console.log('chatMan', chatMan && chatMan[0]);
    getCurrentUserInfo();
    if (chatMan) {
      setChatMan(chatMan[0]);
    }
  }, []);
  useEffect(() => {
    // on：注册一个事件，用来监听 emit 触发的事件。
    // emit和on都可以触发或者监听多个事件，比如连接是一个事件，私聊又是另一个事件，事件名称可以不同
    // 如果是私聊，那么就是把聊天内容收集到之后用emit触发私聊事件，把内容传到服务器，服务器负责转发该内容到私聊的另一个客户端
    // 关键点在于服务器怎么确定私聊的另一方是谁（socket.id）
    // 进来先给服务器socket连接上
    socket.on('connect', () => {
      // 进来之后便给服务器通知我上线了
      socket.emit('online', currentUserRef.current);
    });
  }, []);
    // 监听用户不在线事件
    socket.on("chatman_no_online",()=>{
        setOnLine(false);
    })

   socket.on('reply_private_chat', (data) => {
         setOnLine(true);
         console.log('有人私聊我了1111111111111111111111111111111111111111111111111111111111111111111111111111111111111');
            if(data){
              // 在接收私聊时将isSender改为false
              let newArr = messagesRef.current && messagesRef.current;
              newArr?.push(data);
              newArr && setMessages([...newArr])
              scrollViewRef.current.scrollToEnd({animated: true})
            }
      });

  const handleSendMessage = () => {
    if(onLine){
     if(message && message.trim().length === 0){
            Toast.show('请输入内容再发送', {
              position: Toast.positions.CENTER,
              duration: Toast.durations.LONG,
              shadow: true,
              animation: true,
            });
            return;
          }
          const messageobj = {
            sender:currentUserRef.current?.username,
            receiver:chatManRef.current?.username,
            text:message
          }
          socket.emit('private_chat', messageobj, (data:IMessageObj) => {
            // data是服务器的私聊事件返回的内容，可以自定义
            // 所以无论是接收别人的私聊还是自己私聊别人，都需要渲染消息内容
            let newArr = messages;
            newArr.push(data)
            data && setMessages(newArr);
            setMessage("");
             scrollViewRef.current.scrollToEnd({animated: true})
          })
    } else {
              Toast.show('当前用户不在线', {
                 position: Toast.positions.CENTER,
                 duration: Toast.durations.LONG,
                 shadow: true,
                 animation: true,
              });
    }
  }



  const handleMessageChange = (value: string) => {
    console.log("收集到的value",value);
    setMessage(value);
  };
  const renderMessage = (data:IMessageObj[]) => {
  console.log("data11111",data);
      if(data.length >0){
        return data.map((item,index)=>{
         if(item.isSender){
             return (
                        <View style={styles.messageBoxRight} key={item.createTime+index.toString()}>
                          <View style={styles.boxRight}>
                            <View style={styles.rightTop}>
                               <Text style={styles.createTime}>{item.createTime}</Text>
                                <View><Text>{item.username}</Text></View>
                            </View>
                            <View style={styles.rightBottom}><Text style={styles.rightBottomText}>{item.text}</Text></View>
                          </View>
                            <View style={styles.boxLeft1}>
                              <Image source={{uri: item.scurpture}} style={styles.image}></Image>
                             </View>
                        </View>
                      )
         }else {
             return (
                                    <View style={styles.messageBox} key={item.createTime?item.createTime:index}>
                                        <View style={styles.boxLeft}>
                                          <Image source={{uri: item.scurpture}} style={styles.image}></Image>
                                    </View>
                                      <View style={styles.boxRight}>
                                        <View style={styles.rightTop}>
                                           <View style={styles.username}><Text>{item.username}</Text></View>
                                           <Text>{item.createTime}</Text>
                                        </View>
                                        <View style={styles.rightBottom}><Text style={styles.rightBottomText}>{item.text}</Text></View>
                                      </View>

                                    </View>
                                  )
         }

        }
        )
      }else {
        return <></>
      }

  }
  return (
    <View style={styles.chatBox}>
      <View style={styles.chatMan}>
        <Touchable
          onPress={() => {
            navigation.goBack();
          }}
          style={styles.back}>
          <IconFont name="icon-fanhui" size={22} color={'#A75E5E'}></IconFont>
        </Touchable>
        {/* 聊天对象的名称 */}
        <Text style={styles.chatManText}>{chatManRef.current.username}</Text>
      </View>
      <ScrollView ref={c => scrollViewRef.current = c}>
        {renderMessage(messagesRef.current)}
      </ScrollView>
      <View style={styles.inputBox}>
        <TextInput
          style={styles.textInput}
          value={message}
          onChangeText={handleMessageChange}
        />
        <Touchable onPress={handleSendMessage} style={styles.btnBox}>
          <Text style={styles.btn}>发送</Text>
        </Touchable>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  chatBox: {
    flex: 1,
  },
  chatMan: {
    height: 50,
    backgroundColor: '#fff',
    display:"flex",
    flexDirection:"row",
    alignItems:'center'
  },
  back: {
    paddingRight:5
  },
  chatManText: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#A75E5E',
  },
  inputBox: {
    flexDirection: 'row',
    margin: 5,
  },
  textInput: {
    flex: 1,
    height: 40,
    borderColor: '#ccc',
    borderWidth: 1,
    marginRight: 5,
    borderRadius: 25,
  },
  btnBox: {
    height: 40,
    width: 60,
    backgroundColor: '#A75E5E',
    borderRadius: 50,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  btn: {
    color: 'white',
  },
  messageBox: {
    padding:10,
    display:"flex",
    flexDirection:'row'
  },
  messageBoxRight:{
     padding:10,
     display:"flex",
     flexDirection:'row',
     justifyContent:"flex-end",
  },
  boxLeft: {
    width:50,
    height:50,
    borderRadius:50,
    marginRight:10
  },
  boxLeft1:{
      width:50,
      height:50,
      borderRadius:50,
      marginLeft:10
  },
  image:{
  width:50,
  height:50,
  borderRadius:50
  },
  boxRight: {
    backgroundColor:"#A75E5E",
    paddingRight:20,
    paddingLeft:20,
    paddingTop:10,
    borderRadius:50,
  },
  rightTop:{
    display:"flex",
    flexDirection:"row"
  },
  rightBottom:{

  },
  rightBottomText: {
    fontSize:14
  },
  username:{
    paddingRight:10
  },
  createTime:{
  paddingRight:10
  }
});
export default connector(Chat);
